import { defineStore } from 'pinia'

// 模拟产品数据
const mockProducts = [
  {
    id: '1',
    name: '高性能无线耳机',
    description: '这款无线耳机采用最新蓝牙5.2技术，提供出色的音质和稳定的连接性能。内置主动降噪功能，让您沉浸在音乐世界中。',
    price: 1299,
    originalPrice: 1599,
    discount: '8.1折',
    sales: 1256,
    rating: 4.8,
    reviewCount: 328,
    image: 'https://picsum.photos/seed/headphone1/800/800',
    images: [
      'https://picsum.photos/seed/headphone1/800/800',
      'https://picsum.photos/seed/headphone2/800/800',
      'https://picsum.photos/seed/headphone3/800/800'
    ],
    categoryId: 'electronics',
    specs: [
      {
        name: '颜色',
        options: [
          { value: 'black', label: '曜石黑', price: 1299 },
          { value: 'white', label: '珍珠白', price: 1299 },
          { value: 'blue', label: '星空蓝', price: 1399 }
        ]
      },
      {
        name: '版本',
        options: [
          { value: 'standard', label: '标准版', price: 1299 },
          { value: 'pro', label: 'Pro版', price: 1599 }
        ]
      }
    ],
    reviews: [
      {
        id: '1',
        username: '张三',
        rating: 5,
        content: '音质非常好，降噪效果超出预期，佩戴也很舒适，值得购买！',
        date: '2024-01-15',
        images: []
      },
      {
        id: '2',
        username: '李四',
        rating: 4,
        content: '整体表现不错，续航时间很长，但价格稍微贵了一点。',
        date: '2024-01-10',
        images: []
      }
    ],
    features: [
      '蓝牙5.2技术',
      '主动降噪功能',
      '40小时超长续航',
      'IPX7防水等级',
      '触控操作'
    ],
    // 新增详细信息
    technicalSpecs: {
      connectivity: '蓝牙5.2，支持A2DP、AVRCP、HFP、HSP',
      driverSize: '11mm动态驱动单元',
      frequencyRange: '20Hz - 20kHz',
      impedance: '32Ω',
      sensitivity: '105dB ±3dB',
      batteryCapacity: '耳机45mAh × 2，充电盒580mAh',
      chargingTime: '耳机1.5小时，充电盒2小时',
      workingDistance: '10米',
      microphone: '双麦克风降噪',
      weight: '单耳5.4g，充电盒45g'
    },
    stock: 156,
    shipping: {
      freeShipping: true,
      estimatedDelivery: '2-3天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '12个月质保',
      returnPolicy: '7天无理由退换',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      '无线耳机 × 1副',
      '充电盒 × 1个',
      'USB-C充电线 × 1根',
      '硅胶耳套 × 3对（S/M/L）',
      '使用说明书 × 1本',
      '保修卡 × 1张'
    ],
    tutorial: {
      setupGuide: '开箱后请先将充电盒和耳机充满电，然后开启手机蓝牙搜索配对名称"SoundBuds Pro"，点击连接即可使用。',
      tips: [
        '首次使用前请确保设备电量充足',
        '定期清洁耳机和充电触点以保持良好连接',
        '更新固件可获得更好的使用体验'
      ]
    }
  },
  {
    id: '2',
    name: '轻薄笔记本电脑',
    description: '这款轻薄笔记本采用最新的处理器，性能强劲且散热出色。14英寸全高清屏幕，显示效果细腻。机身轻薄，便于携带。',
    price: 5999,
    originalPrice: 6599,
    discount: '9.1折',
    sales: 856,
    rating: 4.9,
    reviewCount: 156,
    image: 'https://picsum.photos/seed/laptop1/800/800',
    images: [
      'https://picsum.photos/seed/laptop1/800/800',
      'https://picsum.photos/seed/laptop2/800/800',
      'https://picsum.photos/seed/laptop3/800/800'
    ],
    categoryId: 'electronics',
    specs: [
      {
        name: '配置',
        options: [
          { value: 'i5-8gb', label: 'i5/8GB/256GB', price: 5999 },
          { value: 'i7-16gb', label: 'i7/16GB/512GB', price: 7999 }
        ]
      },
      {
        name: '颜色',
        options: [
          { value: 'silver', label: '银色', price: 5999 },
          { value: 'gray', label: '深空灰', price: 5999 }
        ]
      }
    ],
    reviews: [],
    features: [
      '14英寸全高清屏幕',
      '轻薄机身设计',
      '长效电池续航',
      '高速固态硬盘',
      '背光键盘'
    ],
    // 新增详细信息
    technicalSpecs: {
      processor: '第12代英特尔酷睿i5/i7处理器',
      display: '14英寸 FHD (1920×1080) IPS屏幕',
      memory: '8GB/16GB DDR4 3200MHz',
      storage: '256GB/512GB PCIe NVMe SSD',
      graphics: '集成Intel Iris Xe显卡',
      ports: '2×USB-C, 1×USB-A, HDMI, 3.5mm音频接口',
      wireless: 'Wi-Fi 6, Bluetooth 5.2',
      battery: '56Wh锂离子电池',
      weight: '1.2kg',
      dimensions: '322mm × 215mm × 15.9mm',
      operatingSystem: 'Windows 11 家庭版'
    },
    stock: 78,
    shipping: {
      freeShipping: true,
      estimatedDelivery: '3-5天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '24个月整机保修',
      returnPolicy: '7天无理由退换',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      '笔记本电脑 × 1台',
      '电源适配器 × 1个',
      'USB-C充电线 × 1根',
      '使用说明书 × 1本',
      '保修卡 × 1张',
      '快速入门指南 × 1份'
    ],
    tutorial: {
      setupGuide: '首次开机后按照屏幕提示完成Windows设置，连接Wi-Fi并激活系统，然后更新所有驱动程序。',
      tips: [
        '首次使用前请将电池充满',
        '建议安装杀毒软件保护系统安全',
        '定期清理系统垃圾文件可保持良好性能'
      ]
    }
  },
  {
    id: '3',
    name: '智能手表',
    description: '这款智能手表支持心率监测、血氧检测、睡眠跟踪等多种健康功能。还可以接收消息提醒，控制音乐播放，是您的健康助手。',
    price: 899,
    originalPrice: 1299,
    discount: '6.9折',
    sales: 2356,
    rating: 4.7,
    reviewCount: 489,
    image: 'https://picsum.photos/seed/watch1/800/800',
    images: [
      'https://picsum.photos/seed/watch1/800/800',
      'https://picsum.photos/seed/watch2/800/800',
      'https://picsum.photos/seed/watch3/800/800'
    ],
    categoryId: 'electronics',
    specs: [
      {
        name: '颜色',
        options: [
          { value: 'black', label: '黑色', price: 899 },
          { value: 'silver', label: '银色', price: 899 },
          { value: 'pink', label: '粉色', price: 899 }
        ]
      }
    ],
    reviews: [],
    features: [
      '24小时心率监测',
      '血氧饱和度检测',
      '睡眠质量分析',
      '运动模式追踪',
      '消息提醒推送'
    ],
    // 新增详细信息
    technicalSpecs: {
      display: '1.4英寸 AMOLED触控屏，分辨率320×320',
      sensors: '光学心率传感器，血氧传感器，加速度计，陀螺仪',
      waterproof: 'IP68防水防尘',
      battery: '220mAh锂电池',
      standbyTime: '14天',
      workingTime: '5-7天（正常使用）',
      chargingTime: '约2小时',
      compatibility: 'Android 6.0+，iOS 10.0+',
      weight: '32g',
      bandMaterial: '硅胶',
      bandSize: '适合140-220mm腕围'
    },
    stock: 203,
    shipping: {
      freeShipping: true,
      estimatedDelivery: '2-4天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '12个月整机保修',
      returnPolicy: '7天无理由退换',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      '智能手表 × 1个',
      '硅胶表带 × 1条（已安装）',
      '备用表带 × 1条',
      '磁吸式充电底座 × 1个',
      'USB充电线 × 1根',
      '使用说明书 × 1本',
      '保修卡 × 1张'
    ],
    tutorial: {
      setupGuide: '下载"HealthFit"App，打开手表和手机蓝牙，按照App提示完成配对，然后设置个人信息和偏好设置。',
      tips: [
        '保持表带清洁，避免长时间佩戴过紧',
        '运动后及时清洁手表，避免汗水侵蚀',
        '建议每2-3天充电一次以保持最佳体验'
      ]
    }
  },
  {
    id: '4',
    name: '有机棉T恤',
    description: '采用100%有机棉材质，柔软舒适，透气性好。简约时尚的设计风格，适合日常穿着。',
    price: 129,
    originalPrice: 199,
    discount: '6.5折',
    sales: 3521,
    rating: 4.5,
    reviewCount: 892,
    image: 'https://picsum.photos/seed/tshirt1/800/800',
    images: [
      'https://picsum.photos/seed/tshirt1/800/800',
      'https://picsum.photos/seed/tshirt2/800/800',
      'https://picsum.photos/seed/tshirt3/800/800'
    ],
    categoryId: 'clothing',
    specs: [
      {
        name: '尺码',
        options: [
          { value: 's', label: 'S', price: 129 },
          { value: 'm', label: 'M', price: 129 },
          { value: 'l', label: 'L', price: 129 },
          { value: 'xl', label: 'XL', price: 129 }
        ]
      },
      {
        name: '颜色',
        options: [
          { value: 'white', label: '白色', price: 129 },
          { value: 'black', label: '黑色', price: 129 },
          { value: 'gray', label: '灰色', price: 129 }
        ]
      }
    ],
    reviews: [],
    features: [
      '100%有机棉',
      '柔软舒适',
      '简约时尚',
      '多色可选',
      '多种尺码'
    ],
    // 新增详细信息
    technicalSpecs: {
      material: '100%有机棉',
      fabricWeight: '180g/m²',
      thickness: '适中',
      fit: '标准版型',
      collarType: '圆领',
      sleeveType: '短袖',
      stitching: '双针缝边',
      careInstructions: '机洗冷水，悬挂晾干，不可漂白，低温熨烫',
      origin: '中国'
    },
    // 尺码表信息
    sizeChart: {
      's': {
        shoulderWidth: '38cm',
        chest: '88cm',
        length: '68cm',
        sleeveLength: '19cm',
        description: '适合身高160-170cm，体重50-60kg'
      },
      'm': {
        shoulderWidth: '40cm',
        chest: '94cm',
        length: '70cm',
        sleeveLength: '20cm',
        description: '适合身高165-175cm，体重60-70kg'
      },
      'l': {
        shoulderWidth: '42cm',
        chest: '100cm',
        length: '72cm',
        sleeveLength: '21cm',
        description: '适合身高170-180cm，体重70-80kg'
      },
      'xl': {
        shoulderWidth: '44cm',
        chest: '106cm',
        length: '74cm',
        sleeveLength: '22cm',
        description: '适合身高175-185cm，体重80-90kg'
      }
    },
    stock: {
      's': { 'white': 120, 'black': 95, 'gray': 88 },
      'm': { 'white': 150, 'black': 130, 'gray': 110 },
      'l': { 'white': 145, 'black': 125, 'gray': 105 },
      'xl': { 'white': 120, 'black': 100, 'gray': 90 }
    },
    shipping: {
      freeShipping: true,
      estimatedDelivery: '3-5天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '30天质量保证',
      returnPolicy: '15天无理由退换（不影响二次销售）',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      'T恤 × 1件',
      '产品标签 × 1张',
      '购物袋 × 1个'
    ],
    tutorial: {
      setupGuide: '收到商品后，请检查尺码是否合适，如需要退换请保持标签完好。',
      tips: [
        '首次穿着前建议先清洗',
        '避免使用漂白剂，以免损坏衣物',
        '深色衣物建议与浅色衣物分开洗涤'
      ]
    }
  },
  {
    id: '5',
    name: '牛仔裤',
    description: '经典款牛仔裤，采用优质牛仔布材质，耐穿且舒适。修身版型设计，展现完美身材比例。',
    price: 299,
    originalPrice: 399,
    discount: '7.5折',
    sales: 2156,
    rating: 4.6,
    reviewCount: 567,
    image: 'https://picsum.photos/seed/jeans1/800/800',
    images: [
      'https://picsum.photos/seed/jeans1/800/800',
      'https://picsum.photos/seed/jeans2/800/800',
      'https://picsum.photos/seed/jeans3/800/800'
    ],
    categoryId: 'clothing',
    specs: [
      {
        name: '尺码',
        options: [
          { value: '28', label: '28', price: 299 },
          { value: '29', label: '29', price: 299 },
          { value: '30', label: '30', price: 299 },
          { value: '31', label: '31', price: 299 },
          { value: '32', label: '32', price: 299 }
        ]
      },
      {
        name: '颜色',
        options: [
          { value: 'light', label: '浅色', price: 299 },
          { value: 'medium', label: '中色', price: 299 },
          { value: 'dark', label: '深色', price: 299 }
        ]
      }
    ],
    reviews: [],
    features: [
      '优质牛仔布',
      '修身版型',
      '经典款式',
      '耐穿舒适',
      '多尺码选择'
    ],
    // 新增详细信息
    technicalSpecs: {
      material: '98%棉，2%氨纶',
      fabricWeight: '12oz',
      thickness: '中厚',
      fit: '修身版型',
      waistType: '高腰',
      pocketType: '5口袋设计',
      stitching: '双线加固',
      careInstructions: '冷水手洗，悬挂晾干，不可漂白，低温熨烫',
      origin: '中国'
    },
    // 尺码表信息
    sizeChart: {
      '28': {
        waist: '71cm',
        hip: '95cm',
        thigh: '56cm',
        length: '102cm',
        description: '适合腰围71cm，臀围95cm'
      },
      '29': {
        waist: '74cm',
        hip: '98cm',
        thigh: '58cm',
        length: '103cm',
        description: '适合腰围74cm，臀围98cm'
      },
      '30': {
        waist: '76cm',
        hip: '101cm',
        thigh: '60cm',
        length: '104cm',
        description: '适合腰围76cm，臀围101cm'
      },
      '31': {
        waist: '79cm',
        hip: '104cm',
        thigh: '62cm',
        length: '105cm',
        description: '适合腰围79cm，臀围104cm'
      },
      '32': {
        waist: '81cm',
        hip: '107cm',
        thigh: '64cm',
        length: '106cm',
        description: '适合腰围81cm，臀围107cm'
      }
    },
    stock: {
      '28': { 'light': 60, 'medium': 55, 'dark': 50 },
      '29': { 'light': 75, 'medium': 70, 'dark': 65 },
      '30': { 'light': 90, 'medium': 85, 'dark': 80 },
      '31': { 'light': 85, 'medium': 80, 'dark': 75 },
      '32': { 'light': 70, 'medium': 65, 'dark': 60 }
    },
    shipping: {
      freeShipping: true,
      estimatedDelivery: '3-5天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '30天质量保证',
      returnPolicy: '15天无理由退换（不影响二次销售）',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      '牛仔裤 × 1条',
      '产品标签 × 1张',
      '购物袋 × 1个',
      '保养说明卡 × 1张'
    ],
    tutorial: {
      setupGuide: '收到商品后，请试穿检查尺码和舒适度，如需要退换请保持标签完好。',
      tips: [
        '首次穿着前建议用盐水浸泡30分钟，可减少褪色',
        '避免频繁清洗，可延长使用寿命',
        '晾晒时避免阳光直射'
      ]
    }
  },
  {
    id: '6',
    name: '运动鞋',
    description: '专业运动鞋，采用减震科技，提供良好的支撑和舒适性。适合跑步、健身等多种运动场景。',
    price: 499,
    originalPrice: 699,
    discount: '7.1折',
    sales: 1897,
    rating: 4.7,
    reviewCount: 432,
    image: 'https://picsum.photos/seed/shoes1/800/800',
    images: [
      'https://picsum.photos/seed/shoes1/800/800',
      'https://picsum.photos/seed/shoes2/800/800',
      'https://picsum.photos/seed/shoes3/800/800'
    ],
    categoryId: 'clothing',
    specs: [
      {
        name: '尺码',
        options: [
          { value: '39', label: '39', price: 499 },
          { value: '40', label: '40', price: 499 },
          { value: '41', label: '41', price: 499 },
          { value: '42', label: '42', price: 499 },
          { value: '43', label: '43', price: 499 },
          { value: '44', label: '44', price: 499 }
        ]
      },
      {
        name: '颜色',
        options: [
          { value: 'black', label: '黑色', price: 499 },
          { value: 'white', label: '白色', price: 499 },
          { value: 'blue', label: '蓝色', price: 499 }
        ]
      }
    ],
    reviews: [],
    features: [
      '减震科技',
      '透气网面',
      '轻便舒适',
      '耐磨橡胶底',
      '多运动场景适用'
    ],
    // 新增详细信息
    technicalSpecs: {
      upperMaterial: '飞织网面',
      midsole: 'EVA减震中底',
      outsole: '橡胶耐磨大底',
      insole: 'Ortholite透气鞋垫',
      weight: '约280g（单只，42码）',
      closure: '系带设计',
      toeBox: '圆润宽楦设计',
      archSupport: '中等足弓支撑',
      pronationControl: '中性',
      suitableFor: '跑步、健身、日常穿着',
      origin: '中国'
    },
    // 尺码表信息
    sizeChart: {
      '39': {
        footLength: '24.5cm',
        usSize: '7',
        ukSize: '6',
        euSize: '39',
        description: '适合脚长24.0-24.5cm'
      },
      '40': {
        footLength: '25.0cm',
        usSize: '7.5',
        ukSize: '6.5',
        euSize: '40',
        description: '适合脚长24.5-25.0cm'
      },
      '41': {
        footLength: '25.5cm',
        usSize: '8',
        ukSize: '7',
        euSize: '41',
        description: '适合脚长25.0-25.5cm'
      },
      '42': {
        footLength: '26.0cm',
        usSize: '9',
        ukSize: '8',
        euSize: '42',
        description: '适合脚长25.5-26.0cm'
      },
      '43': {
        footLength: '26.5cm',
        usSize: '9.5',
        ukSize: '8.5',
        euSize: '43',
        description: '适合脚长26.0-26.5cm'
      },
      '44': {
        footLength: '27.0cm',
        usSize: '10',
        ukSize: '9',
        euSize: '44',
        description: '适合脚长26.5-27.0cm'
      }
    },
    stock: {
      '39': { 'black': 45, 'white': 50, 'blue': 40 },
      '40': { 'black': 60, 'white': 65, 'blue': 55 },
      '41': { 'black': 75, 'white': 80, 'blue': 70 },
      '42': { 'black': 80, 'white': 85, 'blue': 75 },
      '43': { 'black': 70, 'white': 75, 'blue': 65 },
      '44': { 'black': 50, 'white': 55, 'blue': 45 }
    },
    shipping: {
      freeShipping: true,
      estimatedDelivery: '3-5天',
      shippingMethods: ['快递', '顺丰速运']
    },
    afterSales: {
      warranty: '90天质量保证',
      returnPolicy: '15天无理由退换（不影响二次销售）',
      supportHours: '周一至周日 9:00-21:00'
    },
    packageContents: [
      '运动鞋 × 1双',
      '产品标签 × 1张',
      '鞋盒 × 1个',
      '使用说明书 × 1本',
      '质保卡 × 1张'
    ],
    tutorial: {
      setupGuide: '收到鞋子后，请检查尺码是否合适，新鞋可能需要1-2周的磨合期。',
      tips: [
        '建议运动后及时清洁，保持干燥',
        '避免长时间暴晒和接触化学物质',
        '定期更换鞋垫可保持鞋子内部清洁和舒适性'
      ]
    }
  }
]

// 分类数据
const categories = [
  { id: 'all', name: '全部', icon: '🏠' },
  { id: 'electronics', name: '电子产品', icon: '📱' },
  { id: 'clothing', name: '服装鞋包', icon: '👕' },
  { id: 'home', name: '家居生活', icon: '🏡' },
  { id: 'beauty', name: '美妆个护', icon: '💄' },
  { id: 'food', name: '食品生鲜', icon: '🍎' },
  { id: 'sports', name: '运动户外', icon: '⚽' },
  { id: 'books', name: '图书音像', icon: '📚' }
]

// Banner数据
const banners = [
  {
    id: '1',
    image: 'https://picsum.photos/seed/banner1/1200/400',
    title: '春季新品上市',
    link: '/products?category=clothing',
    description: '探索2024春季最新时尚单品'
  },
  {
    id: '2',
    image: 'https://picsum.photos/seed/banner2/1200/400',
    title: '电子产品大促销',
    link: '/products?category=electronics',
    description: '精选电子产品低至7折'
  },
  {
    id: '3',
    image: 'https://picsum.photos/seed/banner3/1200/400',
    title: '会员专享优惠',
    link: '/user/profile',
    description: '会员购物享额外95折'
  }
]

export const useProductsStore = defineStore('products', {
  state: () => ({
    products: [],
    categories,
    banners,
    filteredProducts: [],
    currentProduct: null,
    searchKeyword: '',
    selectedCategory: 'all',
    sortBy: 'default', // default, price-asc, price-desc, sales
    isLoading: false,
    error: null
  }),
  
  getters: {
    // 通过分类ID获取分类名称
    getCategoryName: (state) => (categoryId) => {
      if (!categoryId) return '未知分类';
      const category = state.categories.find(cat => cat.id === categoryId);
      return category ? category.name : '未知分类';
    },
    
    // 根据分类获取产品
    productsByCategory: (state) => {
      if (state.selectedCategory === 'all') {
        return state.filteredProducts
      }
      return state.filteredProducts.filter(product => product.categoryId === state.selectedCategory)
    },
    
    // 获取排序后的产品
    sortedProducts: (state) => {
      const products = [...state.productsByCategory]
      
      switch (state.sortBy) {
        case 'price-asc':
          return products.sort((a, b) => a.price - b.price)
        case 'price-desc':
          return products.sort((a, b) => b.price - a.price)
        case 'sales':
          return products.sort((a, b) => b.sales - a.sales)
        default:
          return products
      }
    },
    
    // 获取当前分类信息
    currentCategory: (state) => {
      return state.categories.find(cat => cat.id === state.selectedCategory) || state.categories[0]
    }
  },
  
  actions: {
    // 初始化加载产品数据
    async loadProducts() {
      this.isLoading = true
      this.error = null
      
      try {
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 使用模拟数据
        this.products = [...mockProducts]
        this.filteredProducts = [...mockProducts]
      } catch (error) {
        this.error = '加载产品失败'
        console.error('加载产品失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    // 搜索产品
    searchProducts(keyword) {
      this.searchKeyword = keyword
      this.filterProducts()
    },
    
    // 切换分类
    setCategory(categoryId) {
      this.selectedCategory = categoryId
      this.filterProducts()
    },
    
    // 设置排序方式
    setSortBy(sortType) {
      this.sortBy = sortType
    },
    
    // 过滤产品
    filterProducts() {
      let filtered = [...this.products]
      
      // 根据关键词过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(product => 
          product.name.toLowerCase().includes(keyword) ||
          product.description.toLowerCase().includes(keyword)
        )
      }
      
      // 根据分类过滤
      if (this.selectedCategory !== 'all') {
        filtered = filtered.filter(product => product.categoryId === this.selectedCategory)
      }
      
      this.filteredProducts = filtered
    },
    
    // 获取产品详情
    async getProductById(productId) {
      try {
        this.isLoading = true
        this.error = null
        
        // 验证productId参数
        if (!productId) {
          console.error('无效的商品ID: null或undefined')
          return null
        }
        
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 300))
        
        console.log('查找商品ID:', productId)
        console.log('可用商品ID列表:', this.products.map(p => p.id))
        
        // 确保products数组已加载
        if (!this.products || this.products.length === 0) {
          console.error('产品数据未加载')
          // 如果产品数据未加载，初始化模拟数据
          this.products = [...mockProducts]
          console.log('已初始化模拟产品数据')
        }
        
        // 转换ID为字符串并去除空白字符
        const normalizedId = String(productId).trim()
        
        // 增强ID匹配逻辑，使用多种方式尝试匹配
        // 1. 直接字符串匹配
        let product = this.products.find(p => String(p.id) === normalizedId)
        
        // 2. 去除产品ID的空白字符后匹配
        if (!product) {
          product = this.products.find(p => String(p.id).trim() === normalizedId)
        }
        
        // 3. 尝试数字ID匹配（如果ID可以转换为数字）
        if (!product) {
          const numId = Number(normalizedId)
          if (!isNaN(numId)) {
            product = this.products.find(p => Number(p.id) === numId)
          }
        }
        
        // 4. 兜底：如果找不到，返回第一个产品作为默认值
        if (!product && this.products.length > 0) {
          product = this.products[0]
          console.warn('未找到指定商品，返回默认商品:', product.name)
        }
        
        if (product) {
          console.log('找到商品:', product.name)
          this.currentProduct = product
          return product
        } else {
          console.error('产品不存在:', productId)
          return null
        }
      } catch (error) {
        this.error = error.message || '获取产品详情失败'
        console.error('获取产品详情失败:', error)
        
        // 错误情况下，如果有产品数据，返回第一个产品
        if (this.products && this.products.length > 0) {
          const fallbackProduct = this.products[0]
          console.warn('发生错误，返回备用商品:', fallbackProduct.name)
          this.currentProduct = fallbackProduct
          return fallbackProduct
        }
        
        return null
      } finally {
        this.isLoading = false
      }
    },
    
    // 重置筛选条件
    resetFilters() {
      this.searchKeyword = ''
      this.selectedCategory = 'all'
      this.sortBy = 'default'
      this.filteredProducts = [...this.products]
    }
  }
})